package top.zxybird.yun.serialization.thrift;

public class VarintSerializer {

  public static byte[] writeVarint32(int n) {

    // int32最大需要5个字节
    // TODO 内存碎片
    byte[] i32buf = new byte[5];

    int idx = 0;
    while (true) {
      if ((n & ~0x7F) == 0) {
        i32buf[idx++] = (byte) n;
        break;
      } else {
        i32buf[idx] = (byte) ((n & 0x7F) | (0x80));
        n >>>= 7;
      }
    }

    return i32buf;
  }

  public static byte[] writeVarint64(long l) {
    // long64最大需要10个字节
    // TODO 内存碎片
    byte[] varint64buf = new byte[10];
    int idx = 0;
    while (true) {
      if ((l & ~0x7FL) == 0) {
        varint64buf[idx++] = (byte) l;
        break;
      } else {
        varint64buf[idx++] = ((byte) ((l & 0x7F) | (0x80)));
        l >>>= 7;
      }
    }
    return varint64buf;
  }

}
